package netty.ssl.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

/**
 * @Auther: luobiao
 * @Date: 2020/9/22 23:20
 * @Description:
 */
public class ServerMain {
    private static final int m_port = 23333;
    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new Initializer());
            System.out.println("启动了，端口：" + m_port);
            ChannelFuture f = b.bind(m_port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("关闭了");
        }
    }
    public static void main(String[] args) throws Exception {
        new ServerMain().run();
    }

    public class Initializer extends ChannelInitializer<SocketChannel> {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(true);
            pipeline.addLast("ssl", new SslHandler(engine));
           // pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
           // pipeline.addLast(new StringDecoder());
            //pipeline.addLast(new StringEncoder());
            pipeline.addLast(new Handler());
        }
    }
    public class Handler  extends ChannelInboundHandlerAdapter {
      /*  @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            System.out.println("服务器端handlerAdded");
            ByteBuf buf=Unpooled.buffer();
            buf.writeBytes("服务器端handlerAdded".getBytes());
            ctx.writeAndFlush(buf);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();
            System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "在线");
        }*/

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf=(ByteBuf)msg;
            byte[] bs = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bs);
            System.out.println(new String(bs));
            System.out.println("channelRead");
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();
            ctx.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
        }
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            Channel incoming = ctx.channel();
            System.out.println(incoming.remoteAddress() + "掉线");
        }
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            Channel incoming = ctx.channel();
            System.out.println(incoming.remoteAddress() + "异常");
            // 当出现异常就关闭连接
            cause.printStackTrace();
            ctx.close();
        }
    }
}
